package com.gang.music.system.controller;

import com.gang.music.common.AjaxResult;
import com.gang.music.system.entity.Role;
import com.gang.music.system.service.MenuService;
import com.gang.music.system.service.RoleMenuService;
import com.gang.music.system.service.RoleService;
import com.smallchill.core.toolbox.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("/system/role")
@Controller
public class RoleController extends BaseController {

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private RoleMenuService roleMenuService;
	
	@RequestMapping("/list")
	public String roleList(Map<String, Object> map) {
		
		map.put("roleList", roleService.selectList(null));
		
		return "admin/role/roleList";
	}
	
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String roleInput() {
		
		return "admin/role/roleInput";
	}
	
	
	
	@ResponseBody
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public AjaxResult add(Role role, String menuIds) {
		
		try {
			List<Integer> menuIdList = new ArrayList<>();
			for(String menuId : menuIds.split(",")) {
				menuIdList.add(Integer.valueOf(menuId));
			}
			if(Func.isEmpty(role.getId())) {
				roleService.insert(role);
				roleMenuService.insert(role.getId(), menuIdList);
			}else {
				roleService.updateById(role);
				roleMenuService.update(role.getId(), menuIdList);
			}
			return success();
		} catch (Exception e) {
			e.printStackTrace();
			return error("系统出错");
		}
	}
	
	@RequestMapping("/update/{id}")
	public String update(@PathVariable Integer id, 
			Map<String, Object> map) {
		
		if(!Func.isEmpty(id)) {
			map.put("role", roleService.selectById(id));
		}
		return "admin/role/roleInput";
	}
	
	@ResponseBody
	@RequestMapping("/delete/{id}")
	public AjaxResult delete(@PathVariable Integer id) {
		
		try {
			roleService.deleteById(id);
			return success();
		} catch (Exception e) {
			e.printStackTrace();
			return error("系统出错");
		}
	}
}
